package com.djhu.freepartner.web.control.aspect;

import com.djhu.freepartner.core.Status;
import com.djhu.freepartner.core.exception.ServiceException;
import com.djhu.freepartner.web.entity.enums.VerifiyCodeAnno;
import com.djhu.freepartner.web.support.HttpKit;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Aspect
@Component
@Order(-99)
public class VerifiyCodeAspect{

    private static final Logger logger = LoggerFactory.getLogger(VerifiyCodeAspect.class.getName());


    @Autowired
    private RedisTemplate redisTemplate;

    @Pointcut(value = "@annotation(com.djhu.freepartner.web.entity.enums.VerifiyCodeAnno)")
    private void cutPermission() {

    }

    @Around(value = "cutPermission()")
    public Object doVerifiyCode(ProceedingJoinPoint point) throws Throwable{
        MethodSignature ms = (MethodSignature) point.getSignature();
        Method method = ms.getMethod();
        VerifiyCodeAnno verifiyCode = method.getAnnotation(VerifiyCodeAnno.class);
//        long limit = verifiyCode.limit();
//        String ip = HttpKit.getIp();

        //此处可以 根据IP 进行限流
        logger.info("start VerifiyCode check!!!");
        HttpServletRequest request = HttpKit.getRequest();
        String clientverifyCode = request.getParameter("verifycode");
        String validateCode = request.getParameter("validatecode");
        logger.info("receive clientverifyCode is {},validatecode is {}",clientverifyCode,validateCode);
        if (StringUtils.isEmpty(validateCode) || StringUtils.isEmpty(clientverifyCode)){
            logger.error("validateCode or clientverifyCode is null");
            throw new ServiceException(Status.MISSING_VERIFY_CODE);
        }
        String serververifyCode = (String) redisTemplate.opsForValue().get(validateCode);
        logger.error("get serververifyCode from cache,serververifyCode is {},validateCode is {}",serververifyCode,validateCode);
        if (StringUtils.isEmpty(serververifyCode) || clientverifyCode.equals(validateCode)){
            throw new ServiceException(Status.VERIFY_CODE_FAIL);
        }
        return point.proceed();

    }

}
